package com.example.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.JsonReader;
import android.util.Log;

public class FileUtil {
	
	private static final String TAG = "FileUtil";
	
	//不要以斜杠结尾
	final  static String[] settingPath = {"/mnt/sdcard","/mnt/media/sata1/transmission","/mnt/sdcard/transmission"};
	final static String settingFileName = "settings.json";
	
	public static File downloadFile(String url) {
		Log.i(TAG,url);
		File downloadFile = null;
		HttpClient client = new DefaultHttpClient();
		// 新建一个Get方法
		HttpGet get = new HttpGet(url);
		get.addHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
		HttpResponse response = null;
		try {
			response = client.execute(get);
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

			String content = response.getFirstHeader("Content-Disposition")
					.getValue();
			String filename = getContentFileName(content);
			File extDir = new File(FileUtil.getDownLoadPath());
			if(extDir.exists()) {
				File fullFilename = new File(extDir, filename);
				fullFilename.deleteOnExit();
				HttpEntity respEnt = response.getEntity();

				Log.i(TAG,"isChunked" + respEnt.isChunked());
				Log.i(TAG,"Streaming" + respEnt.isStreaming());

				Boolean isStream = respEnt.isStreaming();
				if (isStream) {
					try {
						InputStream fileInStream = respEnt.getContent();
						FileOutputStream fileOutStream = new FileOutputStream(fullFilename);

						byte[] tmpBuf = new byte[1024];
						int tmpLen = 0;
						while ((tmpLen = fileInStream.read(tmpBuf)) > 0) {
							fileOutStream.write(tmpBuf, 0, tmpLen);
						}
						fileOutStream.close();
						downloadFile = fullFilename;
						Log.i(TAG, fullFilename.getName() + " download OK!");
					} catch (IllegalStateException e) {
						Log.i(TAG, fullFilename.getName() + " download Fail!");
						e.printStackTrace();
					} catch (IOException e) {
						Log.i(TAG, fullFilename.getName() + " download Fail!");
						e.printStackTrace();
					} finally {
					}
				}
			}
		}
			
		 
		return downloadFile;
	}
	


	public static Boolean downlodFile(String url, String fullFilename, HttpParams headerParams) throws ClientProtocolException, IOException
	{
	    Boolean downloadOk = Boolean.FALSE;
	     
//	    HttpResponse response = getUrlResponse(url, headerParams, null);
	    HttpClient client = new DefaultHttpClient();
	    // 新建一个Get方法
	    HttpGet get = new HttpGet(url);
	    get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
	    HttpResponse response = client.execute(get);
	    		
	    if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
	        
	        HttpEntity respEnt = response.getEntity();
	        
	        System.out.println("isChunked" + respEnt.isChunked());
	        System.out.println("Streaming" + respEnt.isStreaming());
	         
	        Boolean isStream = respEnt.isStreaming();
	        if(isStream)
	        {
	            try {
	                InputStream fileInStream = respEnt.getContent();
	                FileOutputStream fileOutStream = new FileOutputStream(new File(fullFilename));
	                 
	                byte[] tmpBuf = new byte[1024];
	                int tmpLen = 0;
	                while ( (tmpLen = fileInStream.read(tmpBuf)) > 0 ) {
	                    fileOutStream.write(tmpBuf,0, tmpLen);
	                }
	                fileOutStream.close();
	                downloadOk = Boolean.TRUE;
	            } catch (IllegalStateException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            } catch (IOException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }finally {
	            }
	        }
	    }
	 
	    return downloadOk;
	}
	
	@SuppressLint("NewApi") public static String getDownLoadPath() {
		String downLoad = null;
		for(String path : settingPath) {
			File f = new File(path + "/" + settingFileName);
			if(f.exists()) {
				try {
					JSONTokener jsonParser = new JSONTokener(readFile(f));
					JSONObject httpObj = (JSONObject) jsonParser.nextValue();
					downLoad = httpObj.getString("watch-dir");
					if(null != downLoad && downLoad.trim().length() > 0){
						break;
					}
					Log.i("getDownLoadPath", downLoad);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
		
		return downLoad;
	}
	
	public static String getContentFileName(String contentDisposition){
		String fileName = null;
		if(contentDisposition != null || contentDisposition.indexOf(".") > 0) {
			try {
				fileName = contentDisposition;
				fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("\"") + 1,
						fileName.lastIndexOf("\"")),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return fileName;
	}
	
	
	public static String readFile(File filePath) {
		String jsonString=""; 
        String resultString=""; 
        try {
        	InputStream in = new FileInputStream(filePath);
            StringBuffer bf = new StringBuffer();
            BufferedReader dr=new BufferedReader(new InputStreamReader(in)); 
            while ((jsonString=dr.readLine())!=null) { 
            	bf.append(jsonString); 
            } 
            resultString = bf.toString();
            dr.close();
            in.close();
        } catch (Exception e) { 
            // TODO: handle exception 
        } 
        return resultString; 
	}
	
	public static String getUrlFileName(String fileUrl) {
		String fileName = null;
		try {
//			String imgurl = "文件地址";
			//http://xiacd.com/download.php?id=1943&passkey=b92a4bb1a658aa9876fd151602f18142
			URL url = new URL(fileUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("User-Agent", "	Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0"); 
			conn.connect();

			// 获取文件名和扩展名
			// 先连接一次，解决跳转下载 
			conn.getResponseCode();
			fileUrl = conn.getURL().toString();
			// 第一种方式，针对 img.png
			fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
			String extName = "";
			if (fileName.lastIndexOf(".") > 0) {
				extName = fileName.substring(fileName.lastIndexOf(".") + 1);
			}
			if (extName == null || extName.length() > 4
					|| extName.indexOf("?") > -1) {
				// 第二种方式，获取header 确定文件名和扩展名
				fileName = conn.getHeaderField("Content-Disposition");
				fileName = new String(fileName.getBytes("ISO-8859-1"),"utf8");  
				if (fileName == null || fileName.indexOf("filename") < 0) {
				    SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd   hh:mm:ss");     
				    String date = sDateFormat.format(new java.util.Date());  
					fileName = date;
					extName = "torrent";
				} else {
					Log.i(TAG, fileName);
					fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("\"") + 1,
							fileName.lastIndexOf("\"")),"UTF-8");
					extName = fileName.substring(fileName.lastIndexOf(".") + 1);
				}
			}
			Log.i(TAG, fileName);
			Log.i(TAG, extName);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		
		return fileName;
	}
	
	public static void main(String[] args) {
		getUrlFileName("http://xiacd.com/download.php?id=1950&passkey=b92a4bb1a658aa9876fd151602f18142");
	}
	
}
